<?php
/**
 * Created by PhpStorm.
 * Author: Shadow
 * Date: 2022/6/1
 * Time: 9:20 上午
 * description: GoodsBusiness.php
 */

namespace app\home\business;


use app\common\model\Spec;
use app\common\model\SpecGoods;
use app\common\model\SpecValue;

class GoodsBusiness
{

    /**
     *
     * @param $cate_id 分类
     * @param $sort_field 排序字段
     * @return \app\common\model\Goods|\think\Paginator
     */
    public static function list($cate_id,$sort_field){
        $where = [];
        if ($cate_id > 0) {
            $where[] = ['cate_id','=',$cate_id];
        }

        $goodsList = \app\common\model\Goods::where($where)
            ->order($sort_field,'desc')
            ->field('goods_name,id,goods_price,goods_logo,sort,sales_num,is_new,is_hot,is_recommend')
            ->paginate([
                'list_rows' => 60,
                'query' => [
                    'sort_field' => $sort_field
                ]
            ]);
//       echo  \app\common\model\Goods::getLastSql();die();
        return $goodsList;
    }


    /**
     * 商品详情
     * @param $id
     */
    public static function detail($id) {

        # 商品相册 一个商品对应多个图片 sku表里面查询 规格值的id 从规格值的id查询到规格名id、然后查询到规格名

        $goodsDetail = \app\common\model\Goods::with(['images','specGoods'])->find($id)->toArray();

        $values_ids = array_column($goodsDetail['specGoods'],'value_ids');
        $spec_value_ids = [];
        foreach ($values_ids as $id) {
            $spec_value_ids = array_merge(explode('_',$id),$spec_value_ids);
        }

        $spec_value_ids = array_unique($spec_value_ids);// 获取所有的规格值id
        // 查询规格名称
        $spec_values = SpecValue::whereIn('id',$spec_value_ids)->field('spec_id,spec_value,id')->select()->toArray();
        $spec_ids = array_unique(array_column($spec_values,'spec_id'));
        $spec_name = Spec::whereIn('id',$spec_ids)->field('spec_name,id')->select()->toArray();


        // 处理规格值对应的价格数据
        $price =[];
        foreach ($goodsDetail['specGoods'] as $value) {
            $price[] =[
                'id' => $value['id'],
                'value_ids' => $value['value_ids'],
                'price' => $value['price'],
            ];
        }
        $priceInfo = array_column($price,NULL,'value_ids');

        // 规格名称
        foreach ($spec_name as $key => $value) {
            // 规格值
            foreach ($spec_values as $item) {
                if ($item['spec_id'] == $value['id']) {
                    $spec_name[$key]['spec_values'][] =
                       [
                           'spec_value_id' =>  $item['id'],
                           'spec_value' =>  $item['spec_value'],
                       ];
                }
            }
        }

        // 选中的时候、需要获取选中规格的价格

        $goodsDetail['goods_attr'] = json_decode($goodsDetail['goods_attr'],true);
        $goodsDetail['specGoods'] = $spec_name;// 规格信息
        $goodsDetail['priceInfo'] = json_encode($priceInfo);// 规格值对应的价格信息


        return $goodsDetail;

    }
}